package com.sdk.springbootjwt;

import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> login(@RequestBody User user) {

        String accessToken = JwtUtil.generateAccessToken(user.getUsername());
        String refreshToken = JwtUtil.generateRefreshToken(user.getUsername());
        // 存储RefreshToken到Redis
        redisTemplate.opsForValue().set(
                "jwt:refresh:" + user.getUsername(),
                refreshToken,
                JwtUtil.REFRESH_EXPIRE,
                TimeUnit.MILLISECONDS
        );
        return ResponseEntity.ok(Map.of(
                "accessToken", accessToken,
                "refreshToken", refreshToken
        ));
    }

    @GetMapping("/user")
    public ResponseEntity<String> user(@RequestHeader("Authorization") String accessToken) {
        try {
            String username = JwtUtil.validateToken(accessToken);
            return ResponseEntity.ok(username);
        } catch (Exception e) {
            return ResponseEntity.status(401).build();
        }
    }

    @PostMapping("/refresh")
    public ResponseEntity<String> refreshToken(@RequestHeader("refresh-Token") String refreshToken,
                                               @RequestHeader("Authorization") String oldAccessToken) {
        try {
            String username = JwtUtil.validateToken(refreshToken);

            // 验证Redis中的RefreshToken
            String storedToken = redisTemplate.opsForValue().get("jwt:refresh:" + username);
            if(!refreshToken.equals(storedToken)) {
                throw new RuntimeException("Invalid refresh token");
            }

            // 2. 将旧access_token加入黑名单（剩余TTL=原过期时间）
            long remainingTTL = JwtUtil.getRemainingTime(oldAccessToken); // 获取剩余有效期
            redisTemplate.opsForValue().set(
                    "jwt:blacklist:" + oldAccessToken,
                    "revoked",
                    remainingTTL,
                    TimeUnit.SECONDS
            );

            // 生成新Token
            String newAccessToken = JwtUtil.generateAccessToken(username);
            return ResponseEntity.ok(newAccessToken);
        } catch (Exception e) {
            return ResponseEntity.status(401).build();
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<Void> logout(@RequestHeader("Authorization") String token) {
        try {
            String username = JwtUtil.validateToken(token);
            redisTemplate.delete("jwt:refresh:" + username);
            return ResponseEntity.ok().build();
        } catch (JWTVerificationException e) {
            throw new JWTVerificationException("Invalid token");
        }
    }
}

